/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FrmCliente.java
 *
 * Created on 05-12-2014, 10:16:41 AM
 */
package presentacion;

import Negocios.Cliente;
import Negocios.ListaCliente;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.table.DefaultTableModel;
import java.io.*;
import javax.swing.JOptionPane;
/**
 *
 * @author Estudiante
 */
public class FrmCliente extends javax.swing.JFrame {

    /** Creates new form FrmCliente */
    public FrmCliente() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        TextId = new javax.swing.JTextField();
        TextNombre = new javax.swing.JTextField();
        TextApellidoPaterno = new javax.swing.JTextField();
        TextApellidoMaterno = new javax.swing.JTextField();
        TextFechaNacimiento = new javax.swing.JTextField();
        TextCarnet = new javax.swing.JTextField();
        btnGuardar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        rbmasculino = new javax.swing.JRadioButton();
        rbfemenino = new javax.swing.JRadioButton();
        jLabel8 = new javax.swing.JLabel();
        TextBuscar = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        btnLeer = new javax.swing.JButton();
        btnEscribir = new javax.swing.JButton();
        btnEliminarTexto = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("IdCliente");

        jLabel2.setText("Nombre");

        jLabel3.setText("Apellido Paterno");

        jLabel4.setText("Apellido Materno");

        jLabel5.setText("Fecha de Nacimiento");

        jLabel6.setText("Sexo");

        jLabel7.setText("Carnet");

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        buttonGroup1.add(rbmasculino);
        rbmasculino.setSelected(true);
        rbmasculino.setText("Masculino");

        buttonGroup1.add(rbfemenino);
        rbfemenino.setText("Femenino");

        jLabel8.setText("Buscar por Nombre & CI");

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        btnLeer.setText("Leer Texto");
        btnLeer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLeerActionPerformed(evt);
            }
        });

        btnEscribir.setText("Escribir Texto");
        btnEscribir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEscribirActionPerformed(evt);
            }
        });

        btnEliminarTexto.setText("Eliminar Texto");
        btnEliminarTexto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarTextoActionPerformed(evt);
            }
        });

        btnModificar.setText("Modificar");

        btnEliminar.setText("Eliminar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnGuardar)
                        .addContainerGap())
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel8)
                            .addGap(14, 14, 14)
                            .addComponent(TextBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                            .addGap(18, 18, 18)
                            .addComponent(btnBuscar)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(btnModificar)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(btnEliminar)
                            .addGap(14, 14, 14))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel7)
                                .addComponent(jLabel6)
                                .addComponent(jLabel5)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4))
                                .addComponent(jLabel2))
                            .addGap(30, 30, 30)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(TextFechaNacimiento, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                                .addComponent(TextApellidoPaterno, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                                .addComponent(TextApellidoMaterno, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                                .addComponent(TextCarnet, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                                .addComponent(TextNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(rbmasculino)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(rbfemenino))
                                        .addComponent(TextId, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGap(0, 65, Short.MAX_VALUE)))
                            .addGap(263, 263, 263)))))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnLeer)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEscribir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEliminarTexto)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 254, Short.MAX_VALUE)
                        .addComponent(btnSalir)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TextId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TextNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TextApellidoPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TextApellidoMaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TextFechaNacimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rbmasculino)
                    .addComponent(rbfemenino)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TextCarnet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addGap(8, 8, 8)
                .addComponent(btnGuardar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(TextBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnBuscar)
                        .addComponent(btnModificar)
                        .addComponent(btnEliminar)))
                .addGap(26, 26, 26)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalir)
                    .addComponent(btnLeer)
                    .addComponent(btnEscribir)
                    .addComponent(btnEliminarTexto))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CargarObjetoCliente(Cliente objc){
        objc.setId(Integer.parseInt(this.TextId.getText()));
        objc.setNombreCliente(this.TextNombre.getText());
        objc.setApellidoPaterno(this.TextApellidoPaterno.getText());
        objc.setApellidoMaterno(this.TextApellidoMaterno.getText());
        SimpleDateFormat f = new SimpleDateFormat("dd/mm/yy");
        String fecha = this.TextFechaNacimiento.getText();
        try{
            Date d = f.parse(fecha);
            objc.setFechaNacimiento(d);
        }catch(Exception e){}
        
        if(this.rbmasculino.isSelected())
            objc.setSexo("Masculino");
        if(this.rbfemenino.isSelected())
            objc.setSexo("Femenino");
        objc.setCarnet(Integer.parseInt(this.TextCarnet.getText()));
        
    }

    ListaCliente L = new ListaCliente();

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        
        Cliente objcliente = new Cliente();
        this.CargarObjetoCliente(objcliente);
        L.Insertar(objcliente);
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_btnSalirActionPerformed

     public static boolean EsNumero(String str)  
    {  
         return (str.matches("[+-]?\\d*(\\.\\d+)?") && str.equals("")==false);
    }
    
    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // TODO add your handling code here:
        
    
        List<Cliente> ObjListaCliente = new ArrayList<Cliente>();
        
        if (EsNumero(this.TextBuscar.getText()))
            ObjListaCliente=L.TraerClientePorCarnet(Integer.parseInt(this.TextBuscar.getText()));
        else
            ObjListaCliente=L.TraerClientePorNombre(this.TextBuscar.getText());       
            
        DefaultTableModel modelo=new DefaultTableModel();
        this.jTable1.setModel(modelo);
        
        modelo.addColumn("Id");
        modelo.addColumn("Nombre");
        modelo.addColumn("Apellido Paterno");
        modelo.addColumn("Apellido Materno");
        modelo.addColumn("Fecha de Nacimiento");
        modelo.addColumn("Sexo");
        modelo.addColumn("Carnet");
        
        Iterator iterador=ObjListaCliente.listIterator();
        while(iterador.hasNext()){
                Cliente ObjCliente=(Cliente)iterador.next();
                Object[] fila = new Object[7];
                fila[0]=ObjCliente.getId();
                fila[1]=ObjCliente.getNombreCliente();
                fila[2]=ObjCliente.getApellidoPaterno();
                fila[3]=ObjCliente.getApellidoMaterno();
                fila[4]=ObjCliente.getFechaNacimiento();
                fila[5]=ObjCliente.getSexo();
                fila[6]=ObjCliente.getCarnet();
                modelo.addRow(fila);
        }
    }//GEN-LAST:event_btnBuscarActionPerformed
    private void CargarTextoObjetoCliente(String aux,Negocios.Cliente oc){
        int i=0;
        while(i<=aux.length()-1){
             String a2="";
             while (aux.charAt(i)!=','){
                 a2=a2+aux.charAt(i);
                 i++;
             }
             oc.setId(Integer.parseInt(a2));
             a2="";    
             i++;
             while (aux.charAt(i)!=','){
                 a2=a2+aux.charAt(i);
                 i++;
             }
             oc.setNombreCliente(a2);
             a2="";    
             i++;
             while (aux.charAt(i)!=','){
                  a2=a2+aux.charAt(i);
                  i++;
             }
             oc.setApellidoPaterno(a2);
             a2="";    
             i++;
             while (aux.charAt(i)!=','){
                  a2=a2+aux.charAt(i);
                  i++;
             }
             oc.setApellidoMaterno(a2);
             a2="";    
             i++;
             while (aux.charAt(i)!=','){
                   a2=a2+aux.charAt(i);
                   i++;
             }
             SimpleDateFormat f = new SimpleDateFormat("dd/mm/yy");
             try{
                 Date d= f.parse(a2);
                 oc.setFechaNacimiento(d);
             }catch(Exception e) {}
             a2="";    
             i++;
             while (aux.charAt(i)!=','){
                   a2=a2+aux.charAt(i);
                   i++;
             }
             oc.setSexo(a2);
             a2="";    
             i++;
             while (i<=aux.length()-1){
                    a2=a2+aux.charAt(i);
                    i++;
             }
             oc.setCarnet(Integer.parseInt(a2));
             a2="";
             i++;
        }
    }
    private void LeerTexto(){
        File archivo=null;
        FileReader fr = null;
        BufferedReader br= null;
        try{
            archivo = new File("D:\\clientes.txt");
            fr = new FileReader(archivo);
            br = new BufferedReader(fr);
            String linea;
            while((linea=br.readLine())!=null){
                System.out.println(linea);
                Negocios.Cliente oc = new Negocios.Cliente();
                this.CargarTextoObjetoCliente(linea, oc);
                L.Insertar(oc);
            }            
        }catch(Exception e ){}
    }
    
     private void EscribirTexto(String a){
              File f = new File("D:\\"+a+".txt");
              try {
                  FileWriter fw = new FileWriter(f);
                  BufferedWriter bw = new BufferedWriter(fw);
                  PrintWriter pw = new PrintWriter(bw);
                  
                  List<Cliente> ObjListaCliente = new ArrayList<Cliente>();
                  ObjListaCliente=L.TraerLista();
                  Iterator iterador=ObjListaCliente.listIterator();
                  while(iterador.hasNext()){
                    Cliente ObjCliente=(Cliente)iterador.next();
                    pw.write(Integer.toString(ObjCliente.getId()));
                    pw.append(","+ObjCliente.getNombreCliente());
                    pw.append(","+ObjCliente.getApellidoPaterno());
                    pw.append(","+ObjCliente.getApellidoMaterno());
                    pw.append(","+ObjCliente.getFechaNacimiento());
                    pw.append(","+ObjCliente.getSexo());
                    pw.append(","+ObjCliente.getCarnet());
                    pw.append("\r\n");    
                  }
                  pw.close();
                  bw.close();
              }catch(IOException e){
                  
              }
    }    
    private void btnLeerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLeerActionPerformed
        // TODO add your handling code here:
        this.LeerTexto();
        this.Buscar("0");
    }//GEN-LAST:event_btnLeerActionPerformed

    private void btnEscribirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEscribirActionPerformed
        // TODO add your handling code here:
        this.EscribirTexto(JOptionPane.showInternalInputDialog(TextBuscar, null));
    }//GEN-LAST:event_btnEscribirActionPerformed

private void btnEliminarTextoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarTextoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnEliminarTextoActionPerformed
  private void Buscar(String a){ 
    List<Cliente> ObjListaCliente = new ArrayList<Cliente>();
        
        if (EsNumero(a))
            ObjListaCliente=L.TraerClientePorCarnet(Integer.parseInt(a));
        else
            ObjListaCliente=L.TraerClientePorNombre(a);       
            
        DefaultTableModel modelo=new DefaultTableModel();
        this.jTable1.setModel(modelo);
        
        modelo.addColumn("Id");
        modelo.addColumn("Nombre");
        modelo.addColumn("Apellido Paterno");
        modelo.addColumn("Apellido Materno");
        modelo.addColumn("Fecha de Nacimiento");
        modelo.addColumn("Sexo");
        modelo.addColumn("Carnet");
        
        Iterator iterador=ObjListaCliente.listIterator();
        while(iterador.hasNext()){
                Cliente ObjCliente=(Cliente)iterador.next();
                Object[] fila = new Object[7];
                fila[0]=ObjCliente.getId();
                fila[1]=ObjCliente.getNombreCliente();
                fila[2]=ObjCliente.getApellidoPaterno();
                fila[3]=ObjCliente.getApellidoMaterno();
                fila[4]=ObjCliente.getFechaNacimiento();
                fila[5]=ObjCliente.getSexo();
                fila[6]=ObjCliente.getCarnet();
                modelo.addRow(fila);
        }
    }                          
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FrmCliente().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField TextApellidoMaterno;
    private javax.swing.JTextField TextApellidoPaterno;
    private javax.swing.JTextField TextBuscar;
    private javax.swing.JTextField TextCarnet;
    private javax.swing.JTextField TextFechaNacimiento;
    private javax.swing.JTextField TextId;
    private javax.swing.JTextField TextNombre;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnEliminarTexto;
    private javax.swing.JButton btnEscribir;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnLeer;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton btnSalir;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JRadioButton rbfemenino;
    private javax.swing.JRadioButton rbmasculino;
    // End of variables declaration//GEN-END:variables
}
